<template>
  <el-card>
    <el-tree
    ref="menu-tree"
    node-key="id"
    :default-checked-keys="checkedKeds"
    :data="menus"
    :props="defaultProps"
    show-checkbox
    default-expand-all></el-tree>
    <div class="btn">
      <el-button @click="resetChecked">清空</el-button>
      <el-button type="primary" @click="onSave">保存</el-button>
    </div>
  </el-card>
</template>

<script>
import { getMenuNodeList, allocateRoleMenus, getRoleMenus } from '@/services/menu'

export default {
  name: 'allocMenu',
  props: {
    roleId: {
      type: [Number, String],
      required: true
    }
  },
  data () {
    return {
      menus: [],
      defaultProps: {
        children: 'subMenuList',
        label: 'name'
      },
      checkedKeds: []
    }
  },
  created () {
    // 获取所有菜单并按照层级展示
    this.loadMenus()
    // 获取角色拥有的菜单列表
    this.loadRoleMenus()
  },
  methods: {
    async loadMenus () {
      const { data } = await getMenuNodeList()
      if (data.code === '000000') {
        this.menus = data.data
      }
    },
    async onSave () {
      const { data } = await allocateRoleMenus({
        roleId: this.roleId,
        menuIdList: this.$refs['menu-tree'].getCheckedKeys()
      })
      if (data.code === '000000') {
        this.$message.success('分配菜单成功')
        this.$router.push('/role')
      }
    },
    async loadRoleMenus () {
      const { data } = await getRoleMenus(this.roleId)
      if (data.code === '000000') {
        this.getCheckedKeys(data.data)
      }
    },
    // 自己封装的功能，用于数据筛选功能
    getCheckedKeys (menus) {
      menus.forEach(menu => {
        if (menu.subMenuList) {
          return this.getCheckedKeys(menu.subMenuList)
        }
        if (menu.selected) {
          this.checkedKeds = [...this.checkedKeds, menu.id]
        }
      })
    },
    // 清空按钮
    resetChecked () {
      this.$refs['menu-tree'].setCheckedKeys([])
    }
  }
}
</script>

<style lang='scss' scoped>
  .btn {
    margin: 20px;
    float: right;
  }
</style>
